package cn.mumzone.pos.ui.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.github.jdsjlzx.ItemDecoration.GridItemDecoration;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.base.BaseActivity;
import cn.mumzone.basic.dialog.AlertDialog;
import cn.mumzone.basic.util.AppDateUtil;
import cn.mumzone.basic.util.BigDecimalUtil;
import cn.mumzone.basic.util.DisplayUtil;
import cn.mumzone.basic.util.ItemClickSupport;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.MoneyFormatUtil;
import cn.mumzone.basic.util.NetUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.basic.util.ToastUtil;
import cn.mumzone.basic.util.log.Elog;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.basic.loading.button.LoadingButton;
import cn.mumzone.pos.R;
import cn.mumzone.pos.dialog.PosAlertDialog;
import cn.mumzone.pos.dialog.PosDialog;
import cn.mumzone.pos.event.BindMemberEntity;
import cn.mumzone.pos.event.MemberChangeEvent;
import cn.mumzone.pos.event.GoodsAmountChangedEvent;
import cn.mumzone.pos.event.RefreshMemberLevelEvent;
import cn.mumzone.pos.event.RemoveServiceEvent;
import cn.mumzone.pos.model.GoodsEntity;
import cn.mumzone.pos.model.MemberEntity;
import cn.mumzone.pos.model.ReserveOrderEntity;
import cn.mumzone.pos.model.ServerEntity;
import cn.mumzone.pos.model.ServerResultEntity;
import cn.mumzone.pos.model.ServiceEntity;
import cn.mumzone.pos.presenter.OpenOrderPresenter;
import cn.mumzone.pos.presenter.contract.OpenOrderContract;
import cn.mumzone.pos.ui.adapter.ADA_CartGoods;
import cn.mumzone.pos.ui.adapter.ADA_CartServices;
import cn.mumzone.pos.ui.adapter.ADA_DialogChooseServerList;
import cn.mumzone.pos.ui.fragment.FRA_OpenOrderGoods;
import cn.mumzone.pos.ui.fragment.FRA_OpenOrderService;
import cn.mumzone.pos.ui.widgets.keyboard.PosKeyBoardView;
import cn.mumzone.pos.util.AddMemberUtil;
import cn.mumzone.pos.util.AppUtil;
import cn.mumzone.pos.util.GoodsUtil;
import cn.mumzone.pos.util.LedDisplayUtil;
import cn.mumzone.pos.util.PopupUtil;

/**
 * Created by qiuzhenhuan on 2019/6/13.
 */

public class ACT_OpenOrder extends BaseActivity<OpenOrderPresenter> implements OpenOrderContract.View {

    private static final String KEY_RESERVE = "key_reserve";
    private static final String KEY_RESERVE_ID = "key_reserve_id";

    /**
     * 本地维护的购物车数据
     */
    private final LinkedList<GoodsEntity> mOpenOrderCartList = new LinkedList<>();

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rb_goods)
    RadioButton rbGoods;
    @BindView(R.id.rb_service)
    RadioButton rbService;

    @BindView(R.id.tv_name_birthday)
    TextView tvNameBirthday;
    @BindView(R.id.tv_phone_birthday)
    TextView tvPhoneBirthday;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_add_member)
    TextView tvAddMember;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_vip)
    TextView tvVip;
    @BindView(R.id.rl_reserve_time)
    RelativeLayout rlReserveTime;

    @BindView(R.id.iv_avator)
    ImageView ivAvator;
    @BindView(R.id.iv_add_or_unbind_member)
    ImageView ivAddOrUnbindMember;
    @BindView(R.id.tv_reserve_time)
    TextView tvReserveTime;

    @BindView(R.id.ll_cart_goods)
    LinearLayout llCartGoods;
    @BindView(R.id.rv_cart_goods)
    LRecyclerView rvCartGoods;
    @BindView(R.id.ll_empty_cart)
    LinearLayout llEmptyCart;


    @BindView(R.id.ll_cart_services)
    LinearLayout llCartServices;
    @BindView(R.id.rv_cart_services)
    LRecyclerView rvCartServices;

    @BindView(R.id.tv_reserve_status)
    TextView tvReserveStatus;
    @BindView(R.id.btn_close_reserve)
    Button btnCloseReserve;

    @BindView(R.id.rl_reserve_person)
    RelativeLayout rlReservePerson;
    @BindView(R.id.tv_reserve_person)
    TextView tvReservePerson;

    @BindView(R.id.rl_settle)
    RelativeLayout rlSettle;
    @BindView(R.id.rl_arrived)
    RelativeLayout rlArrived;

    @BindView(R.id.tv_select_count)
    TextView tvSelectCount;
    @BindView(R.id.tv_select_price)
    TextView tvSelectPrice;
    @BindView(R.id.btn_order_or_settle)
    LoadingButton btnOrderOrSettle;

    FRA_OpenOrderGoods mFraGoods;
    FRA_OpenOrderService mFraService;
    Fragment mDefaultFragment;
    Fragment mCurrFragment;

    private AlertDialog updateServerDialog;
    private LRecyclerView rvChooseServerList;
    private ADA_DialogChooseServerList mServerAdapter;
    private ServiceEntity mSelectService;

    private ADA_CartGoods mCartGoodsAdapter;
    private ADA_CartServices mCartServiceAdapter;

    private ReserveOrderEntity mReserveOrder;

    private String mReserveId;

    private boolean isCurrentGoods;

    private boolean isJustReserve;

    private boolean isGoingToSettle = false;

    private boolean isFirstSwitch;

    private MemberEntity mSelectMember;

    private PosAlertDialog deleteServiceDialog;
    private PosAlertDialog closeReserveDialog;
    private PosAlertDialog unBindMemberDialog;
    private AlertDialog mEditGoodsDialog;

    private LedDisplayUtil ledDisplayUtil;

    private PopupWindow mMemberPopup;

    public MemberEntity getSelectMember() {
        return mSelectMember;
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        mReserveOrder = (ReserveOrderEntity) extras.getSerializable(KEY_RESERVE);
        mReserveId = extras.getString(KEY_RESERVE_ID);

    }

    @Override
    protected void initVariable() {
        ledDisplayUtil = new LedDisplayUtil(mContext);
        isJustReserve = mReserveOrder != null || !StringUtils.isEmpty(mReserveId);
        isCurrentGoods = !isJustReserve;

        if (mReserveOrder != null) {
            if (mSelectMember == null && !StringUtils.isEmpty(mReserveOrder.getBillingUser())) {
                mSelectMember = new MemberEntity();
                mSelectMember.setMemberId(StringUtils.get(mReserveOrder.getBillingUser()));
                mSelectMember.setName(StringUtils.get(mReserveOrder.getBillName()));
                mSelectMember.setPhone(StringUtils.get(mReserveOrder.getBillPhone()));
                mSelectMember.setBirthday(StringUtils.get(mReserveOrder.getBillBirthday()));
                mSelectMember.setDiscountType(StringUtils.get(mReserveOrder.getBillDiscountType()));
            }
        }

        isFirstSwitch = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        resetSettleButton();
    }

    @Override
    protected void initEventAndData() {


        initGoodsCartList();

        initServicesCartList();

        initUpdateServerDialog();

        showCartListStatus(true);

        showMemberInfo();

        initFragment();

        switchView();

        initViewByReserveData();

        updateSelectCountAndAmountForService();


        mPresenter.initEvent();
        RxBus.getDefault().post(new RefreshMemberLevelEvent());


        if (!StringUtils.isEmpty(mReserveId)) {
            mPresenter.loadReserveDetail(mReserveId);
        }

        showPopupHint();

    }

    private void initViewByReserveData() {
        if (!isJustReserve || mReserveOrder == null) {
            tvReserveStatus.setVisibility(View.GONE);
            btnCloseReserve.setVisibility(View.GONE);
            rlReserveTime.setVisibility(View.GONE);
            rlReservePerson.setVisibility(View.GONE);
        } else {
            //显示预约详情
            tvReserveStatus.setVisibility(View.VISIBLE);
            btnCloseReserve.setVisibility(View.VISIBLE);
            switch (mReserveOrder.getStatus()) {
                case ReserveOrderEntity.ORDER_STATUS_RESERVED:
                    rlReserveTime.setVisibility(View.VISIBLE);
                    tvReserveStatus.setText("（已预约）");
                    tvReserveTime.setText(AppDateUtil.getDateToString(Long.valueOf(mReserveOrder.getAppointmentTime()), AppDateUtil.MM_DD_HH_MM));
                    tvReserveStatus.setTextColor(getResources().getColor(R.color.order_status_reserve));
                    if (AppUtil.hasServiceBusiness()) {
                        rlSettle.setVisibility(View.GONE);
                        rlArrived.setVisibility(View.VISIBLE);
                    } else {
                        rlSettle.setVisibility(View.VISIBLE);
                        rlArrived.setVisibility(View.GONE);
                    }
                    break;
                case ReserveOrderEntity.ORDER_STATUS_ARRIVED:
                    rlReserveTime.setVisibility(View.GONE);
                    tvReserveStatus.setTextColor(getResources().getColor(R.color.order_status_service));
                    tvReserveStatus.setText("（服务中）");
                    rlSettle.setVisibility(View.VISIBLE);
                    rlArrived.setVisibility(View.GONE);
                    break;
            }
            rlReservePerson.setVisibility(!StringUtils.isEmpty(mReserveOrder.getCouponType())
                    && "1".equals(mReserveOrder.getCouponType()) ? View.GONE : View.VISIBLE);
            tvReservePerson.setText(String.format("%s（%s）",
                    StringUtils.isEmpty(mReserveOrder.getUserName()) ?
                            StringUtils.isEmpty(mReserveOrder.getMemberCompanyId()) ? "散客" : "暂无姓名"
                            : mReserveOrder.getUserName(), StringUtils.get(mReserveOrder.getUserPhone())));

            if (!ListUtil.isListEmpty(mReserveOrder.getServices())) {
                showCartListStatus(false);
                mCartServiceAdapter.setData(mReserveOrder.getServices());
                mCartServiceAdapter.notifyDataSetChanged();
            }
        }
    }

    private void initFragment() {
        if (!isJustReserve) {
            mFraGoods = new FRA_OpenOrderGoods();
        }
        if (isJustReserve) {
            mFraService = FRA_OpenOrderService.getInstance(mReserveOrder);
        } else {
            mFraService = new FRA_OpenOrderService();
        }

        mDefaultFragment = isCurrentGoods ? mFraGoods : mFraService;
        if (!mDefaultFragment.isAdded()) {
            mCurrFragment = mDefaultFragment;
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.add(R.id.fl_content_layout, mDefaultFragment);
            transaction.commitAllowingStateLoss();
        }

    }

    private void switchView() {
        rbGoods.setChecked(isCurrentGoods);
        rbService.setChecked(!isCurrentGoods);
        llCartGoods.setVisibility(isCurrentGoods ? View.VISIBLE : View.GONE);
        llCartServices.setVisibility(isCurrentGoods ? View.GONE : View.VISIBLE);

        if (isJustReserve) {
            tvTitle.setVisibility(View.VISIBLE);
            rbGoods.setVisibility(View.GONE);
            rbService.setVisibility(View.GONE);
        } else {
            tvTitle.setVisibility(View.GONE);
            rbGoods.setVisibility(View.VISIBLE);
            rbService.setVisibility(View.VISIBLE);
        }

        resetSettleButton();

        if (isCurrentGoods) {
            updateSelectCountAndAmountForGoods();
        } else {
            updateSelectCountAndAmountForService();
        }

    }

    private void resetAdapterPopupHint() {
        mCartGoodsAdapter.dismissPopup();
        mCartServiceAdapter.dismissPopup();

        if (isCurrentGoods) {
            int[] rvPosition = new int[2];
            rvCartGoods.getLocationOnScreen(rvPosition);
            int offset = mCartGoodsAdapter.getAnchorViewPosition() - rvPosition[1];
            if (offset > 0) {
                mCartGoodsAdapter.notifyDataSetChanged();
            }
        } else {
            int[] rvPosition = new int[2];
            rvCartServices.getLocationOnScreen(rvPosition);
            int offset = mCartServiceAdapter.getAnchorViewPosition() - rvPosition[1];
            if (offset > 0) {
                mCartServiceAdapter.notifyDataSetChanged();
            }
        }

    }

    private void resetSettleButton() {
        if (!isCurrentGoods) {
            if (!isJustReserve && AppUtil.hasServiceBusiness()) {
                //产康
                btnOrderOrSettle.setBackgroundResource(R.drawable.btn_selector_black_confirm);
                btnOrderOrSettle.stopLoading("下单");
            } else {
                //小儿游泳
                btnOrderOrSettle.setBackgroundResource(R.drawable.btn_selector_red_confirm);
                btnOrderOrSettle.stopLoading("结账");
            }
        } else {
            //商品
            btnOrderOrSettle.setBackgroundResource(R.drawable.btn_selector_red_confirm);
            btnOrderOrSettle.stopLoading("结账");
        }
    }


    private void initServicesCartList() {
        rvCartServices.setLayoutManager(new LinearLayoutManager(mContext));
        mCartServiceAdapter = new ADA_CartServices(mContext);
        rvCartServices.setAdapter(new LRecyclerViewAdapter(mCartServiceAdapter));
        rvCartServices.setHasFixedSize(true);
        rvCartServices.setLoadMoreEnabled(false);
        rvCartServices.setPullRefreshEnabled(false);

        mCartServiceAdapter.setOnItemDeleteListener(new ADA_CartServices.OnItemDeleteListener() {
            @Override
            public void onItemDeleted(final int position) {
                if (ListUtil.isListEmpty(mCartServiceAdapter.getData())) {
                    return;
                }

                deleteServiceDialog = new PosAlertDialog.Builder(mContext)
                        .setRemindText("确认要删除服务吗？")
                        .setPrimaryText("确认删除")
                        .setPrimaryLoadingText("删除中")
                        .setUseLoadingButton(true)
                        .setOnConfirmClickListener(new PosAlertDialog.OnConfirmClickListener() {
                            @Override
                            public void onConfirmClick(View view, Dialog dialog) {
                                if (isJustReserve && mCartServiceAdapter.getData().size() == 1) {
                                    mPresenter.doDeleteReserve(mReserveOrder.getId());
                                    return;
                                }
                                mSelectService = mCartServiceAdapter.getData().get(position);
                                if (isJustReserve) {
                                    mPresenter.doDeleteSubReserve(mSelectService.getId());
                                } else {
                                    RxBus.getDefault().post(new RemoveServiceEvent(mSelectService));
                                    mCartServiceAdapter.getData().remove(position);
                                    mCartServiceAdapter.notifyDataSetChanged();
                                    updateSelectCountAndAmountForService();
                                    if (ListUtil.isListEmpty(mCartServiceAdapter.getData())) {
                                        showCartListStatus(true);
                                    }
                                    deleteServiceDialog.cancelLoading();
                                    PosToast.INSTANCE.makeCheckMarkToast(mContext, "已删除");
                                    updateSelectCountAndAmountForService();
                                }
                            }
                        }).build();
                deleteServiceDialog.show();

            }
        });

        ItemClickSupport.addTo(rvCartServices).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                mCartServiceAdapter.dismissPopup();
                mSelectService = mCartServiceAdapter.getData().get(position - 1);
                if (isJustReserve) {
                    ArrayList<ServiceEntity> serviceList = new ArrayList<>();
                    serviceList.add(mSelectService);
                    mPresenter.loadServerList(ServerEntity.UPDATE_TYPE_UPDATE, mReserveOrder.getId(),
                            AppDateUtil.getDateToString(Long.valueOf(mReserveOrder.getAppointmentTime()), AppDateUtil.YYYY_MM_DD_HH_MM),
                            serviceList);
                } else {
                    mPresenter.loadServerList(ServerEntity.UPDATE_TYPE_NEW, "",
                            AppDateUtil.getDateToString(System.currentTimeMillis(), AppDateUtil.YYYY_MM_DD_HH_MM_SS),
                            mCartServiceAdapter.getData());
                }
            }
        });

        initScrollListenerForPopup(rvCartServices, null, mCartServiceAdapter);

    }

    private void initGoodsCartList() {
        if (isJustReserve) {
            return;
        }
        rvCartGoods.setLayoutManager(new LinearLayoutManager(mContext));
        mCartGoodsAdapter = new ADA_CartGoods(mContext);
        mCartGoodsAdapter.setOnGoodsAmountChangedListener(new ADA_CartGoods.OnGoodsAmountChangedListener() {
            @Override
            public void onAmountChanged(int position) {
                mPresenter.addGoodsToCart(false, mOpenOrderCartList);
            }

            @Override
            public void onGoodsDeleted(final int position) {
                new PosAlertDialog.Builder(mContext)
                        .setRemindText("确认要删除商品吗？")
                        .setOnConfirmClickListener(new PosAlertDialog.OnConfirmClickListener() {
                            @Override
                            public void onConfirmClick(View view, Dialog dialog) {
                                GoodsEntity mDeletedEntity = mCartGoodsAdapter.getDataList().get(position - 1);
                                mDeletedEntity.setSelectCount(0);
                                mOpenOrderCartList.remove(position - 1);
                                mCartGoodsAdapter.getDataList().remove(position - 1);
                                mCartGoodsAdapter.notifyDataSetChanged();
                                updateSelectCountAndAmountForGoods();
                                if (ListUtil.isListEmpty(mCartGoodsAdapter.getDataList())) {
                                    showCartListStatus(true);
                                }
                                RxBus.getDefault().post(new GoodsAmountChangedEvent(mOpenOrderCartList));
                                PosToast.INSTANCE.makeCheckMarkToast(mContext, "已删除");
                            }
                        }).build().show();
            }
        });
        mCartGoodsAdapter.setOnEditGoodsListener(new ADA_CartGoods.OnEditGoodsListener() {
            @Override
            public void onEditGoodsInfo(GoodsEntity entity) {
                mEditGoodsDialog = GoodsUtil.showEditGoodsDialog(mContext, entity, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mPresenter.addGoodsToCart(true, mOpenOrderCartList);
                    }
                });
            }

            @Override
            public void onEditGoodsPrice(GoodsEntity entity) {
                AlertDialog dialog = showModifyBargainDialog(null, entity);
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        mPresenter.addGoodsToCart(false, mOpenOrderCartList);
                    }
                });
            }
        });
        rvCartGoods.setAdapter(new LRecyclerViewAdapter(mCartGoodsAdapter));
        rvCartGoods.setHasFixedSize(true);
        rvCartGoods.setLoadMoreEnabled(false);
        rvCartGoods.setPullRefreshEnabled(false);

        initScrollListenerForPopup(rvCartGoods, mCartGoodsAdapter, null);
    }

    private void initScrollListenerForPopup(LRecyclerView recyclerView, final ADA_CartGoods goodsAdapter, final ADA_CartServices serviceAdapter) {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {

                int[] rvPosition = new int[2];
                recyclerView.getLocationOnScreen(rvPosition);

                if (goodsAdapter != null) {

                    int offset = goodsAdapter.getAnchorViewPosition() - rvPosition[1];

                    if (offset < 0) {
                        if (goodsAdapter.isPopupShowing()) {
                            goodsAdapter.dismissPopup();
                        }
                    } else {
                        if (!goodsAdapter.isPopupShowing()) {
                            goodsAdapter.notifyDataSetChanged();
                        }
                    }

                } else if (serviceAdapter != null) {
                    int offset = serviceAdapter.getAnchorViewPosition() - rvPosition[1];

                    if (offset < 0) {
                        if (serviceAdapter.isPopupShowing()) {
                            serviceAdapter.dismissPopup();
                        }
                    } else {
                        if (!serviceAdapter.isPopupShowing()) {
                            serviceAdapter.notifyDataSetChanged();
                        }
                    }
                }

            }
        });
    }

    private AlertDialog showModifyBargainDialog(final TextView tvTarget, final GoodsEntity entity) {

        final AlertDialog bargainDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_modify_bargain_price)
                .setDialogNoConfirm()
                .setDialogTitle("修改议价金额")
                .setWidth(438)
                .show();

        TextView originPrice = bargainDialog.getView(R.id.tv_origin_price);
        originPrice.setText(entity.getPrice());

        final EditText etModify = bargainDialog.getView(R.id.et_modify);
        etModify.setHint(entity.getBargainPrice());
        MoneyFormatUtil.formatMoney(etModify, null);
        PosKeyBoardView keyBoardView = bargainDialog.getView(R.id.keyboard_view);
        keyBoardView.attachTo(etModify);
        keyBoardView.setOnConfirmClickListener(new PosKeyBoardView.OnConfirmClickListener() {
            @Override
            public void onConfirmClick(String text) {
                String bargainPrice = MoneyFormatUtil.getFormattedMoney(text, false);
                if (TextUtils.isEmpty(bargainPrice)) {
                    ToastUtil.makeText(mContext, "议价金额不可以为零！", false);
                    return;
                }
                ledDisplayUtil.displayPrice(bargainPrice);
                if (tvTarget != null) tvTarget.setText(bargainPrice);
                entity.setBargainPrice(bargainPrice);
                bargainDialog.dismiss();
            }
        });

        return bargainDialog;
    }

    private void initUpdateServerDialog() {
        updateServerDialog = new PosDialog.PosBuilder(mContext)
                .setRealDialogContent(R.layout.dialog_choose_server)
                .setDialogTitle("修改技师")
                .setDialogNoConfirm()
                .setWidthAndHeight(428, 350)
                .create();

        rvChooseServerList = updateServerDialog.getView(R.id.server_list);
        GridLayoutManager manager = new GridLayoutManager(mContext, 2);
        rvChooseServerList.setLayoutManager(manager);
        mServerAdapter = new ADA_DialogChooseServerList(mContext);
        rvChooseServerList.setAdapter(new LRecyclerViewAdapter(mServerAdapter));
        GridItemDecoration divider = new GridItemDecoration.Builder(mContext)
                .setHorizontal(R.dimen.dp_22)
                .setVertical(R.dimen.dp_20)
                .setColorResource(android.R.color.transparent)
                .build();
        rvChooseServerList.addItemDecoration(divider);

        rvChooseServerList.setHasFixedSize(true);
        rvChooseServerList.setPullRefreshEnabled(false);
        rvChooseServerList.setLoadMoreEnabled(false);

        ItemClickSupport.addTo(rvChooseServerList).setOnItemClickListener(new ItemClickSupport.OnItemClickListener() {
            @Override
            public void onItemClicked(RecyclerView recyclerView, int position, View v) {
                ServerEntity serverEntity = mServerAdapter.getData().get(position - 1);
                if (isJustReserve) {
                    if (serverEntity.getTechnicianId().equals(mSelectService.getTechnicianId())) {
                        closeDialog(updateServerDialog);
                        return;
                    }
                    mPresenter.doUpdateReserveServer(mSelectService.getId(), serverEntity.getTechnicianId(), serverEntity.getTechnicianName());
                } else {
                    closeDialog(updateServerDialog);
                    mServerAdapter.setDefaultServerId("");
                    if (serverEntity.getTechnicianId().equals(mSelectService.getTechnicianId())) {
                        return;
                    }
                    mSelectService.setTechnicianId(serverEntity.getTechnicianId());
                    mSelectService.setTechnicianName(serverEntity.getTechnicianName());
                    mCartServiceAdapter.notifyDataSetChanged();
                    PosToast.INSTANCE.makeCheckMarkToast(mContext, "已修改");
                }
            }
        });
    }

    private void showCartListStatus(boolean isListNull) {
        llCartGoods.setVisibility(isListNull || rbService.isChecked() ? View.GONE : View.VISIBLE);
        llCartServices.setVisibility(isListNull || rbGoods.isChecked() ? View.GONE : View.VISIBLE);
        llEmptyCart.setVisibility(isListNull ? View.VISIBLE : View.GONE);
        btnOrderOrSettle.setEnabled(!isListNull);
    }

    private void showMemberInfo() {
        tvAddMember.setVisibility(mSelectMember == null || StringUtils.isEmpty(mSelectMember.getPhone()) ? View.VISIBLE : View.INVISIBLE);
        tvVip.setVisibility(mSelectMember != null && !StringUtils.isEmpty(mSelectMember.getMemberId()) ? View.VISIBLE : View.INVISIBLE);
        if (mSelectMember != null && !StringUtils.isEmpty(mSelectMember.getMemberId())) {
            if (!StringUtils.isEmpty(mSelectMember.getBirthday()) && AppDateUtil.isBirthdayDay(new Date(),
                    AppDateUtil.timeStamp2Date(mSelectMember.getBirthday()))) {
                tvName.setVisibility(View.INVISIBLE);
                tvPhone.setVisibility(View.INVISIBLE);
                tvNameBirthday.setVisibility(View.VISIBLE);
                tvPhoneBirthday.setVisibility(View.VISIBLE);
                tvBirthday.setVisibility(View.VISIBLE);
            } else {
                tvName.setVisibility(View.VISIBLE);
                tvPhone.setVisibility(View.VISIBLE);
                tvNameBirthday.setVisibility(View.INVISIBLE);
                tvPhoneBirthday.setVisibility(View.INVISIBLE);
                tvBirthday.setVisibility(View.INVISIBLE);
            }
        } else {
            tvName.setVisibility(View.INVISIBLE);
            tvPhone.setVisibility(View.INVISIBLE);
            tvNameBirthday.setVisibility(View.INVISIBLE);
            tvPhoneBirthday.setVisibility(View.INVISIBLE);
            tvBirthday.setVisibility(View.INVISIBLE);

        }

        if (!isJustReserve) {
            mCartGoodsAdapter.setBindMember(mSelectMember);
//            mCartGoodsAdapter.notifyDataSetChanged();
        }
        mCartServiceAdapter.setBindMember(mSelectMember);
        mCartServiceAdapter.notifyDataSetChanged();

        if (mSelectMember == null || StringUtils.isEmpty(mSelectMember.getMemberId())) {
            ivAddOrUnbindMember.setImageResource(R.drawable.svg_ic_add_member_open_order);
        } else {
            tvPhone.setText(StringUtils.getString(mSelectMember.getPhone()));
            tvPhoneBirthday.setText(StringUtils.getString(mSelectMember.getPhone()));
            ivAddOrUnbindMember.setImageResource(R.drawable.svg_ic_open_order_link);
            if (mSelectMember != null && !StringUtils.isEmpty(mSelectMember.getMemberId())) {
                tvName.setTextColor(getResources().getColor(R.color.member_color));
                tvNameBirthday.setTextColor(getResources().getColor(R.color.member_color));
                tvPhone.setTextColor(getResources().getColor(R.color.member_color));
                tvPhoneBirthday.setTextColor(getResources().getColor(R.color.member_color));
                tvName.setText(StringUtils.isEmpty(mSelectMember.getName()) ?
                        "暂无姓名" : StringUtils.getString(mSelectMember.getName()));
                tvNameBirthday.setText(StringUtils.isEmpty(mSelectMember.getName()) ?
                        "暂无姓名" : StringUtils.getString(mSelectMember.getName()));
            } else {
                tvName.setTextColor(getResources().getColor(R.color.white_color));
                tvNameBirthday.setTextColor(getResources().getColor(R.color.white_color));
                tvPhone.setTextColor(getResources().getColor(R.color.white_color));
                tvPhoneBirthday.setTextColor(getResources().getColor(R.color.white_color));
                tvName.setText(StringUtils.isEmpty(mSelectMember.getName()) ?
                        "散客" : StringUtils.getString(mSelectMember.getName()));
                tvNameBirthday.setText(StringUtils.isEmpty(mSelectMember.getName()) ?
                        "散客" : StringUtils.getString(mSelectMember.getName()));
            }
        }

        // 刷新金额
        if (isCurrentGoods) {
//            updateSelectCountAndAmountForGoods();
        } else {
            updateSelectCountAndAmountForService();
        }


    }


    @OnClick({R.id.rb_goods, R.id.rb_service, R.id.ic_back, R.id.iv_add_or_unbind_member, R.id.btn_order_or_settle, R.id.btn_close_reserve,
            R.id.rl_member_layout, R.id.tv_arrived, R.id.rl_reserve_time})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rb_goods:
                if (isJustReserve) {
                    return;
                }
                isCurrentGoods = true;
                switchView();
                showCartListStatus(ListUtil.isListEmpty(mCartGoodsAdapter.getDataList()));
                switchContent(mCurrFragment, mFraGoods);
                resetAdapterPopupHint();
                break;
            case R.id.rb_service:
                isCurrentGoods = false;
                switchView();
                showCartListStatus(ListUtil.isListEmpty(mCartServiceAdapter.getData()));
                switchContent(mCurrFragment, mFraService);
                if (!isJustReserve && isFirstSwitch) {
                    mFraService.setMember(mSelectMember);
                    isFirstSwitch = false;
                }
                resetAdapterPopupHint();
                break;
            case R.id.ic_back:
                finish();
                break;
            case R.id.iv_add_or_unbind_member:
                boolean isMemberNull = mSelectMember == null || StringUtils.isEmpty(mSelectMember.getPhone());
                PopupUtil.dismissPopup(isMemberNull ? PopupUtil.OPEN_ORDER_ADD_MEMBER : PopupUtil.OPEN_ORDER_UNBIND_MEMBER,
                        mMemberPopup);
                AddMemberUtil.doSthAboutMemberBinding(mContext, isMemberNull, mPresenter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        unBindMemberDialog = (PosAlertDialog) dialog;
                        if (isJustReserve) {
                            mPresenter.doUpdateReserveMember(mReserveOrder.getId(), null);
                        } else {
                            mSelectMember = null;
                            showMemberInfo();
                            RxBus.getDefault().post(new MemberChangeEvent(null));
                            unBindMemberDialog.cancelLoading();
                            PosToast.INSTANCE.makeCheckMarkToast(mContext, "已解绑");
                            mPresenter.loadRemoteGoodsPrice(mCartGoodsAdapter.getDataList(), mSelectMember);
                        }
                    }
                });
                break;
            case R.id.btn_order_or_settle:
                if (isCurrentGoods) {

                    // 判断当前购物车有无寄存商品，如果有寄存商品，但是没有绑定会员的，弹窗要求绑定会员
                    if (checkGoodsRegisterStatus() && mSelectMember == null) {
                        isGoingToSettle = true;
                        AddMemberUtil.showSelectMemberDialog(mContext, mPresenter);
                        return;
                    }

                    btnOrderOrSettle.startLoading("生成账单");
                    mPresenter.checkGoodInInventory(mCartGoodsAdapter.getDataList());
//                    ACT_SettleAccounts.startAc(mContext, mSelectMember == null ? "" : StringUtils.get(mSelectMember.getPhone()), JSON.toJSONString(mCartGoodsAdapter.getDataList()), ACT_SettleAccounts.SETTLE_ORDER_TYPE_GOODS, false);

                } else {
                    if (isJustReserve) {
                        if (AppDateUtil.compareDate(new Date(), AppDateUtil.timeStamp2Date(mReserveOrder.getAppointmentTime()))) {
                            showError("只有当天的预约单才能结账");
                            return;
                        }

                        if (AppUtil.hasBabySwimBusiness() &&
                                Long.parseLong(mReserveOrder.getAppointmentTime()) > System.currentTimeMillis()) {
                            PosAlertDialog dialog = new PosAlertDialog.Builder(mContext)
                                    .setRemindText("结账后会立即开始服务计时，确定要现在结账吗？")
                                    .setOnConfirmClickListener(new PosAlertDialog.OnConfirmClickListener() {
                                        @Override
                                        public void onConfirmClick(View view, Dialog dialog) {
                                            ACT_SettleAccounts.startAc(mContext, mSelectMember == null ? "" : StringUtils.get(mSelectMember.getPhone()), JSON.toJSONString(mCartServiceAdapter.getData()), ACT_SettleAccounts.SETTLE_ORDER_TYPE_SERVICE, false);
                                        }
                                    }).build();
                            dialog.show();
                        } else {
                            btnOrderOrSettle.startLoading("生成账单");
                            ACT_SettleAccounts.startAc(mContext, mSelectMember == null ? "" : StringUtils.get(mSelectMember.getPhone()), JSON.toJSONString(mCartServiceAdapter.getData()), ACT_SettleAccounts.SETTLE_ORDER_TYPE_SERVICE, false);
                        }
                    } else {

                        btnOrderOrSettle.startLoading("正在下单");

                        mPresenter.doAddReserve(mSelectMember != null ? mSelectMember.getMemberId() : "",
                                mSelectMember != null ? mSelectMember.getName() : "",
                                mSelectMember != null ? mSelectMember.getPhone() : "", mCartServiceAdapter.getData());
                    }
                }
                break;
            case R.id.btn_close_reserve:
                closeReserveDialog = new PosAlertDialog.Builder(mContext)
                        .setRemindText("关闭不可恢复，确认要关闭吗？")
                        .setUseLoadingButton(true)
                        .setPrimaryText("确认关闭")
                        .setPrimaryLoadingText("正在关闭")
                        .setOnConfirmClickListener(new PosAlertDialog.OnConfirmClickListener() {
                            @Override
                            public void onConfirmClick(View view, Dialog dialog) {
                                mPresenter.doDeleteReserve(mReserveOrder.getId());
                            }
                        }).build();
                showDialog(closeReserveDialog);
                break;
            case R.id.rl_member_layout:
                if (mSelectMember != null && !StringUtils.isEmpty(mSelectMember.getMemberId()) && !StringUtils.isEmpty(mSelectMember.getPhone())) {
                    ACT_MemberDetail.startAc(mContext, mSelectMember.getMemberId(), mSelectMember.getPhone());
                } else {
//                    showDialog(selectMemberDialog);
                    AddMemberUtil.showSelectMemberDialog(mContext, mPresenter);
                }
                break;
            case R.id.tv_arrived:
                if (AppDateUtil.compareDate(new Date(), AppDateUtil.timeStamp2Date(mReserveOrder.getAppointmentTime()))) {
                    showError("只有当天的预约单才能开始服务");
                    return;
                }
                mPresenter.doConfirmArrived(mReserveOrder.getId());
                break;
            case R.id.rl_reserve_time:
                ACT_UpdateReserveTime.startAc(mContext, mReserveOrder);
                break;

        }
    }

    public void switchContent(Fragment from, Fragment to) {
        if (null != to && mCurrFragment != to) {

            mCurrFragment = to;
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            if (!to.isAdded()) { // 先判断是否被add过
                transaction.hide(from).add(R.id.fl_content_layout, to).commitAllowingStateLoss();
            } else {
                transaction.hide(from).show(to).commitAllowingStateLoss();
            }
        }
    }

    @Override
    public void showGoodsAdded(List<GoodsEntity> goodsEntityList) {

        if (!ListUtil.isListEmpty(goodsEntityList)) {
            ledDisplayUtil.displayPrice(mSelectMember != null &&
                    !StringUtils.isEmpty(mSelectMember.getMemberId()) ?
                    StringUtils.get(goodsEntityList.get(0).getMemberPrice(), goodsEntityList.get(0).getPrice()) :
                    goodsEntityList.get(0).getPrice());
        }
        // 更新购物车列表
        updateLocalCartList(goodsEntityList);

        mPresenter.addGoodsToCart(false, mOpenOrderCartList);

    }

    @Override
    public void showAddGoodsSuccess(boolean isModify) {

        if (isModify) {
            PosToast.INSTANCE.makeCheckMarkToast(mContext, "已修改");
            mEditGoodsDialog.dismiss();
        }

        showCartListStatus(false);
        mCartGoodsAdapter.update(mOpenOrderCartList, true);

        // 计算商品金额
        updateSelectCountAndAmountForGoods();

        // 添加到购物车成功后，通知 Fragment 刷新页面
        RxBus.getDefault().post(new GoodsAmountChangedEvent(mOpenOrderCartList));

    }

    @Override
    public void showSettleSuccess() {
        finish();
    }

    @Override
    public void showConfirmArrivedSuccess() {
        mReserveOrder.setStatus(ReserveOrderEntity.ORDER_STATUS_ARRIVED);
        initViewByReserveData();
    }

    @Override
    public void showReserveTimeChanged(String date) {
        mReserveOrder.setAppointmentTime(date);
        tvReserveTime.setText(AppDateUtil.getDateToString(Long.valueOf(mReserveOrder.getAppointmentTime()), AppDateUtil.MM_DD_HH_MM));
    }

    @Override
    public void showReserveDetail(ReserveOrderEntity entity) {
        mReserveOrder = entity;
        mFraService.setOrderEntity(entity);
        if (mSelectMember == null && !StringUtils.isEmpty(mReserveOrder.getBillingUser())) {
            mSelectMember = new MemberEntity();
            mSelectMember.setMemberId(StringUtils.get(mReserveOrder.getBillingUser()));
            mSelectMember.setName(StringUtils.get(mReserveOrder.getBillName()));
            mSelectMember.setPhone(StringUtils.get(mReserveOrder.getBillPhone()));
            mSelectMember.setBirthday(StringUtils.get(mReserveOrder.getBillBirthday()));
            mSelectMember.setDiscountType(StringUtils.get(mReserveOrder.getBillDiscountType()));
            RxBus.getDefault().post(new MemberChangeEvent(mSelectMember));
        }
        showMemberInfo();
        initViewByReserveData();

        updateSelectCountAndAmountForService();
    }

    private void updateSelectCountAndAmountForGoods() {

        int totalCount = 0;
        if (!ListUtil.isListEmpty(mOpenOrderCartList)) {
            for (GoodsEntity goodsEntity : mOpenOrderCartList) {
                totalCount += goodsEntity.getSelectCount();
            }
        }
        tvSelectCount.setText(StringUtils.getString(totalCount));

        double amount = 0.0d;
        if (!ListUtil.isListEmpty(mCartGoodsAdapter.getDataList())) {
            for (GoodsEntity entity : mCartGoodsAdapter.getDataList()) {
                String goodsPrice = GoodsUtil.getGoodsPriceByMember(mSelectMember, entity);
                String goodsCount = StringUtils.get(Integer.parseInt(entity.getGoodsCount()) - entity.getPresentNum());
                amount = BigDecimalUtil.add(String.valueOf(amount),
                        String.valueOf(BigDecimalUtil.mul(goodsCount, goodsPrice)));
            }
        }
        tvSelectPrice.setText(StringUtils.getFormattedMoneyWithUnit(String.valueOf(amount)));
    }

    /**
     * 更新本地购物车列表
     *
     * @param goodsEntityList
     */
    private void updateLocalCartList(List<GoodsEntity> goodsEntityList) {

        outerLoop:
        for (int i = 0; i < goodsEntityList.size(); i++) {
            GoodsEntity recentAddGoodsBean = goodsEntityList.get(i).clone();
            for (int j = 0; j < mOpenOrderCartList.size(); j++) {
                GoodsEntity localCartBean = mOpenOrderCartList.get(j);

                // 获取到购物车列表后，与内存中列表数据进行 id 匹配
                String recentAddGoodsSpecJson = JSON.toJSONString(recentAddGoodsBean.getGoodsSpec());
                String localGoodsSpecJson = JSON.toJSONString(localCartBean.getGoodsSpec());

                if (recentAddGoodsBean.getGoodsId().equals(localCartBean.getGoodsId())
                        && recentAddGoodsSpecJson.hashCode() == localGoodsSpecJson.hashCode()) {

                    // 如果是同一个商品，更新商品数量和寄存数量
                    localCartBean.setGoodsCount(getCount(localCartBean.getGoodsCount(), recentAddGoodsBean.getGoodsCount()));
                    localCartBean.setRegisterCount(getCount(localCartBean.getRegisterCount(), recentAddGoodsBean.getRegisterCount()));
                    localCartBean.setSelectCount(Integer.parseInt(localCartBean.getGoodsCount()));

                    continue outerLoop;
                }

            }
            // 如果有新数据，则插入链表最后
            recentAddGoodsBean.setSelectCount(recentAddGoodsBean.getSelectCount() + 1);
            mOpenOrderCartList.addFirst(recentAddGoodsBean);
        }
    }

    private String getCount(String origin, String newAdd) {
        int originNum = Integer.parseInt(origin);
        int newAddNum = Integer.parseInt(newAdd);
        return StringUtils.get(originNum + newAddNum);
    }

    @Override
    public void showServiceAdded(ServiceEntity serviceEntity) {
        showCartListStatus(false);
        if (ListUtil.isListEmpty(mCartServiceAdapter.getData())) {
            ArrayList<ServiceEntity> data = new ArrayList<>();
            data.add(serviceEntity);
            mCartServiceAdapter.setData(data);
            mCartServiceAdapter.notifyDataSetChanged();
        } else {
            mCartServiceAdapter.getData().add(serviceEntity);
            mCartServiceAdapter.notifyDataSetChanged();
        }

        updateSelectCountAndAmountForService();
    }

    private void updateSelectCountAndAmountForService() {
        tvSelectCount.setText(StringUtils.getString(mCartServiceAdapter.getItemCount()));
        double amount = 0.0d;
        if (!ListUtil.isListEmpty(mCartServiceAdapter.getData())) {
            for (ServiceEntity entity : mCartServiceAdapter.getData()) {
                amount = BigDecimalUtil.add(String.valueOf(amount),
                        mSelectMember != null && !StringUtils.isEmpty(mSelectMember.getMemberId()) ?
                                MemberEntity.DISCOUNT_TYPE_MEMBER_PRICE.equals(mSelectMember.getDiscountType()) ?
                                        entity.getMemberPrice() : entity.getOriginPrice() : entity.getOriginPrice());
            }
        }
        tvSelectPrice.setText(StringUtils.getFormattedMoneyWithUnit(String.valueOf(amount)));
    }

    @Override
    public void showError(String msg) {
        if (closeReserveDialog != null && closeReserveDialog.isShowing()) {
            closeReserveDialog.cancelLoading();
        }
        if (deleteServiceDialog != null && deleteServiceDialog.isShowing()) {
            deleteServiceDialog.cancelLoading();
        }
        super.showError(msg);

        if (closeReserveDialog != null && closeReserveDialog.isShowing()) {
            closeReserveDialog.cancelLoading();
        }
        if (deleteServiceDialog != null && deleteServiceDialog.isShowing()) {
            deleteServiceDialog.cancelLoading();
        }
        resetSettleButton();
    }

    @Override
    public void showServerList(ServerResultEntity serverResultEntity) {
        if (!ListUtil.isListEmpty(serverResultEntity.getList())) {

            updateServerDialog.toggleShowEmpty(false, R.id.root_view);
            mServerAdapter.setData(serverResultEntity.getList());
            rvChooseServerList.setAdapter(new LRecyclerViewAdapter(mServerAdapter));

            // 根据数据集大小设置弹窗高度
            // 默认高度 300，如果超过 8 条数据，高度就高一点
            if (serverResultEntity.getList().size() > 4) {
                ViewGroup.LayoutParams params = rvChooseServerList.getLayoutParams();
                params.height = Math.min(DisplayUtil.dip2px(mContext, 260), params.height *= 1.3);
                rvChooseServerList.setLayoutParams(params);
            }
        } else {

            if (serverResultEntity.isScheduleOrTechnician()) {
                updateServerDialog.toggleShowEmpty(true, R.id.root_view, R.drawable.svg_ic_empty_server, "您还没有排班哦~",
                        "立即排班", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (AppConstants.TEMP_USER_PERMISSION != null && AppConstants.TEMP_USER_PERMISSION.isScheduling()) {
                                    ACT_Schedule.startAc(mContext);
                                } else {
                                    PosToast.INSTANCE.makeShortToast(mContext, "无排班权限");
                                }
                            }
                        });
            } else {
                updateServerDialog.toggleShowEmpty(true, R.id.root_view, R.drawable.svg_ic_empty_server, "您还没有添加技师哦~");
            }
        }

        showDialog(updateServerDialog);
        mServerAdapter.setDefaultServerId(mSelectService.getTechnicianId());
        rvChooseServerList.setAdapter(new LRecyclerViewAdapter(mServerAdapter));
    }

    @Override
    public void showAddReserveSuccess(ReserveOrderEntity reserveOrderEntity) {
        resetSettleButton();
        if (AppUtil.hasServiceBusiness()) {
            //产康
            ToastUtil.makeText(mContext, "下单成功", false);
            finish();
        } else {
            //小儿游泳
            ACT_SettleAccounts.startAc(mContext, mSelectMember != null ? mSelectMember.getPhone() : "",
                    JSON.toJSONString(reserveOrderEntity.getServices()), ACT_SettleAccounts.SETTLE_ORDER_TYPE_BABY_SWIM, false);
        }

    }

    @Override
    public void showDeleteSubReserveSuccess() {
        if (deleteServiceDialog != null && deleteServiceDialog.isShowing()) {
            deleteServiceDialog.cancelLoading();
        }
        RxBus.getDefault().post(new RemoveServiceEvent(mSelectService));
        mCartServiceAdapter.getData().remove(mSelectService);
        mCartServiceAdapter.notifyDataSetChanged();
        if (ListUtil.isListEmpty(mCartServiceAdapter.getData())) {
            showCartListStatus(true);
        }
        PosToast.INSTANCE.makeCheckMarkToast(mContext, "已删除");
        updateSelectCountAndAmountForService();
    }

    @Override
    public void showCloseReserveSuccess() {
        if (closeReserveDialog != null && closeReserveDialog.isShowing()) {
            closeReserveDialog.cancelLoading();
        }
        if (deleteServiceDialog != null && deleteServiceDialog.isShowing()) {
            deleteServiceDialog.cancelLoading();
        }

        PosToast.INSTANCE.makeCheckMarkToast(mContext, "已关闭");
        finish();
    }

    @Override
    public void showUpdateServerSuccess(String technicianId, String technicianName) {
        closeDialog(updateServerDialog);
        mServerAdapter.setDefaultServerId("");
        mSelectService.setTechnicianId(technicianId);
        mSelectService.setTechnicianName(technicianName);
        mCartServiceAdapter.notifyDataSetChanged();
        PosToast.INSTANCE.makeCheckMarkToast(mContext, "已修改");
    }

    @Override
    public void showAddMemberSuccess(MemberEntity memberEntity) {

        if (isJustReserve) {
            PosToast.INSTANCE.makeToast(mContext, PosToast.ToastType.TOAST_TYPE_SQUARE,
                    PosToast.ToastSquareLevel.ALERT_SUCCESS_SQUARE, "添加成功~", false);
            mPresenter.doUpdateReserveMember(mReserveOrder.getId(), memberEntity);
        } else {
            mSelectMember = memberEntity;
            mSelectMember.setMemberId(memberEntity.getId());
            showMemberInfo();

            RxBus.getDefault().post(new MemberChangeEvent(memberEntity));
            RxBus.getDefault().post(new BindMemberEntity());
            mPresenter.loadRemoteGoodsPrice(mCartGoodsAdapter.getDataList(), mSelectMember);


            PosToast.INSTANCE.makeToast(mContext, PosToast.ToastType.TOAST_TYPE_SQUARE,
                    PosToast.ToastSquareLevel.ALERT_SUCCESS_SQUARE, "添加成功~", false);
        }

    }

    @Override
    public void showSearchMemberSuccess(MemberEntity memberEntity) {
        if (isJustReserve) {
            mPresenter.doUpdateReserveMember(mReserveOrder.getId(), memberEntity);
        } else {
            this.mSelectMember = memberEntity;
            RxBus.getDefault().post(new MemberChangeEvent(mSelectMember));
            RxBus.getDefault().post(new BindMemberEntity());
            showMemberInfo();
            PosToast.INSTANCE.makeCheckMarkToast(mContext, "已绑定");
            mPresenter.loadRemoteGoodsPrice(mCartGoodsAdapter.getDataList(), mSelectMember);

            if (isGoingToSettle) { // 跳转结账
                btnOrderOrSettle.startLoading("生成账单");
                ACT_SettleAccounts.startAc(mContext, mSelectMember == null ? "" : StringUtils.get(mSelectMember.getPhone()), JSON.toJSONString(mCartGoodsAdapter.getDataList()), ACT_SettleAccounts.SETTLE_ORDER_TYPE_GOODS, true);
                isGoingToSettle = false;
            }
        }
        showPopupHint();
    }

    @Override
    public void showUpdateMemberSuccess(MemberEntity memberEntity) {
        this.mSelectMember = memberEntity;
        RxBus.getDefault().post(new MemberChangeEvent(mSelectMember));
        RxBus.getDefault().post(new BindMemberEntity());
        showMemberInfo();
        if (unBindMemberDialog != null && unBindMemberDialog.isShowing()) {
            unBindMemberDialog.cancelLoading();
            PosToast.INSTANCE.makeCheckMarkToast(mContext, "已解绑");
        }
        mCartServiceAdapter.notifyDataSetChanged();
        updateSelectCountAndAmountForService();
    }

    @Override
    public void showGoodsPriceChanged() {
        if (isCurrentGoods) {
            mCartGoodsAdapter.update(mOpenOrderCartList, true);

            // 计算商品金额
            updateSelectCountAndAmountForGoods();
        }
    }

    @Override
    public void showServicePriceChanged() {
        if (!isCurrentGoods) {
            mCartServiceAdapter.notifyDataSetChanged();
            updateSelectCountAndAmountForService();
        }
    }

    @Override
    public void showCheckResult(List<GoodsEntity> goodsEntities) {
        btnOrderOrSettle.stopLoading("结账");
        if (ListUtil.isListEmpty(goodsEntities)) {
            ACT_SettleAccounts.startAc(mContext, mSelectMember == null ? "" : StringUtils.get(mSelectMember.getPhone()), JSON.toJSONString(mCartGoodsAdapter.getDataList()), ACT_SettleAccounts.SETTLE_ORDER_TYPE_GOODS, false);
        } else {
            StringBuilder builder = new StringBuilder();
            for (int index = 0; index < goodsEntities.size(); index++) {
                GoodsEntity goodsEntity = goodsEntities.get(index);
                builder.append(goodsEntity.getGoodsName());
                if (index < goodsEntities.size() - 1) {
                    builder.append("\n");
                }
            }
            GoodsUtil.showCheckGoodsInventoryResultDialog(mContext, "以下商品正在盘点，无法售卖", builder.toString());
        }
    }

    @Override
    public void showSyncRemoteGoodsPrice(List<GoodsEntity> list) {
        if (!ListUtil.isListEmpty(list)) {
            for (GoodsEntity localGood : mCartGoodsAdapter.getDataList()) {
                for (GoodsEntity remoteGood : list) {
                    if (localGood.getGoodsSkuId().equals(remoteGood.getGoodsSkuId())) {
                        localGood.setPrice(remoteGood.getPrice());
                        localGood.setMemberPrice(remoteGood.getMemberPrice());
                        localGood.setSecondPrice(remoteGood.getSecondPrice());
                        break;
                    }
                }
            }
            mCartGoodsAdapter.notifyDataSetChanged();
        }
    }


    @Override
    protected int getLayout() {
        return R.layout.act_open_order;
    }

    /**
     * 购物车列表是否有寄存商品，有的话需要强制绑定会员
     *
     * @return
     */
    private boolean checkGoodsRegisterStatus() {
        for (GoodsEntity entity : mOpenOrderCartList) {
            if (!StringUtils.isEmpty(entity.getRegisterCount()) && Integer.parseInt(entity.getRegisterCount()) > 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 正常开单页面
     *
     * @param context
     */
    public static void startAc(Context context) {

        if (!NetUtil.isNetworkAvailable(context)) {
            PosToast.INSTANCE.makeShortToast(context, "网络不给力，请稍候再试");
            return;
        }

        Intent intent = new Intent(context, ACT_OpenOrder.class);
        context.startActivity(intent);
    }

    /**
     * 首页跳转预约详情
     *
     * @param context
     * @param reserveOrderEntity
     */
    public static void startAc(Context context, ReserveOrderEntity reserveOrderEntity) {

        if (!NetUtil.isNetworkAvailable(context)) {
            PosToast.INSTANCE.makeShortToast(context, "网络不给力，请稍候再试");
            return;
        }

        Intent intent = new Intent(context, ACT_OpenOrder.class);
        intent.putExtra(KEY_RESERVE, reserveOrderEntity);
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (ledDisplayUtil != null) {
            ledDisplayUtil.clear();
        }
    }

    /**
     * 预约页面跳转详情
     *
     * @param context
     * @param reserveId
     */
    public static void startAc(Context context, String reserveId) {

        if (!NetUtil.isNetworkAvailable(context)) {
            PosToast.INSTANCE.makeShortToast(context, "网络不给力，请稍候再试");
            return;
        }

        Intent intent = new Intent(context, ACT_OpenOrder.class);
        intent.putExtra(KEY_RESERVE_ID, reserveId);
        context.startActivity(intent);
    }

    public List<ServiceEntity> getCartServices() {
        return mCartServiceAdapter.getData();
    }

    public LinkedList<GoodsEntity> getCartList() {
        return mOpenOrderCartList;
    }

    public void showPopupHint() {
        rvChooseServerList.postDelayed(new Runnable() {
            @Override
            public void run() {
                mMemberPopup = PopupUtil.showBlackBgPopup(ivAddOrUnbindMember,
                        mSelectMember == null ? PopupUtil.OPEN_ORDER_ADD_MEMBER : PopupUtil.OPEN_ORDER_UNBIND_MEMBER,
                        mSelectMember == null ? "点击快捷添加会员" : "点击解绑会员", PopupUtil.LEFT_TOP);

            }
        }, 800);
    }

}
